## Carregando pacotes exigidos: rgdal
## Carregando pacotes exigidos: sp
## Please note that rgdal will be retired by the end of 2023,
## plan transition to sf/stars/terra functions using GDAL and PROJ
## at your earliest convenience.
## 
## rgdal: version: 1.5-28, (SVN revision 1158)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.2.1, released 2020/12/29
## Path to GDAL shared files: C:/Users/tamer/Documents/R/win-library/4.1/rgdal/gdal
## GDAL binary built with GEOS: TRUE 
## Loaded PROJ runtime: Rel. 7.2.1, January 1st, 2021, [PJ_VERSION: 721]
## Path to PROJ shared files: C:/Users/tamer/Documents/R/win-library/4.1/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.4-6
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
## Overwritten PROJ_LIB was C:/Users/tamer/Documents/R/win-library/4.1/rgdal/proj
## Carregando pacotes exigidos: raster
## Carregando pacotes exigidos: tmap
## Carregando pacotes exigidos: maptools
## Checking rgeos availability: TRUE
## Please note that 'maptools' will be retired by the end of 2023,
## plan transition at your earliest convenience;
## some functionality will be moved to 'sp'.
## Carregando pacotes exigidos: tidyverse
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.8
## v tidyr   1.2.0     v stringr 1.4.0
## v readr   2.1.2     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x tidyr::extract() masks raster::extract()
## x dplyr::filter()  masks stats::filter()
## x dplyr::lag()     masks stats::lag()
## x dplyr::select()  masks raster::select()
## Carregando pacotes exigidos: broom
## Carregando pacotes exigidos: knitr
## Carregando pacotes exigidos: kableExtra
## 
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## Carregando pacotes exigidos: RColorBrewer
## Carregando pacotes exigidos: plotly
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:raster':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
## Carregando pacotes exigidos: htmlwidgets
## Carregando pacotes exigidos: weathermetrics
## Carregando pacotes exigidos: glue
## 
## Attaching package: 'glue'
## The following object is masked from 'package:raster':
## 
##     trim
# Sign up for free on the site:https://openweathermap.org/api and enter your api in the code below 
import csv
import requests

api_key = 'bc656b9222f7f091184dccaa5d217f50'

# Clear the csv for new consulting
f = open("temp_pennsylvania.csv", "w")
f.truncate()
f.close()

header_added = False
with open("data_long_lat.csv", 'r', newline="",encoding='latin-1') as file:
  reader = csv.reader(file, delimiter=';')
  for row in reader:
    latlongwheater = f'http://api.openweathermap.org/data/2.5/weather?lat={row[1]}&lon={row[2]}&units=metric&appid={api_key}'
    source = requests.get(latlongwheater)
    temp_local = source.json()['main']['temp']
    
    with open("./temp_pennsylvania.csv", "a", newline="",encoding='latin-1') as file2:
      writer = csv.writer(file2, delimiter=',')
      if not header_added:
        writer.writerow(['NM_MUNICIP','TEMP'])
        header_added = True
      writer.writerow([row[0], temp_local])
# 1. LOADING AND MERGING THE DATA

# Loading shapefile from EUA-Pennsylvania -------------------------------------------------
shp_pennsylvania <- readOGR(dsn = "PaCounty", layer = "PaCounty2022_01")
## Warning in OGRSpatialRef(dsn, layer, morphFromESRI = morphFromESRI, dumpSRS =
## dumpSRS, : Discarded datum NAD 83 in Proj4 definition: +proj=poly +lat_0=40.925
## +lon_0=-77.75 +x_0=0 +y_0=0 +ellps=GRS80 +units=m +no_defs
#To access a shapefile database, we must use the @ operator:
shp_pennsylvania@data %>% 
  kable() %>%
  kable_styling(bootstrap_options = "striped", 
                full_width = TRUE, 
                font_size = 12)


#Loading the previously constructed temperature table
tabel_temp<- read.csv(file = 'temp_pennsylvania.csv')

#Convert from Celsius to Fahrenheit
tabel_temp$TEMP <- celsius.to.fahrenheit(T.celsius =as.numeric(tabel_temp$TEMP),round = 2 )

# Capitalize the NM_MUNICIP column of the table_file to be ready to merge with the shapefile
tabel_temp$NM_MUNICIP = toupper(tabel_temp$NM_MUNICIP)

# Merge the shapefile with the table_temp
shp_dados_pennsylvania <- merge(x =shp_pennsylvania,
                               y = tabel_temp,
                               by.x = "COUNTY_NAM",
                               by.y = "NM_MUNICIP")


# 2. VISUALIZATION OF SPATIAL DATA

# Using ggplot2:

# Step 1: Transform the shapefile into a data frame object and then
# import data not already in the shapefile into the new data frame object.

shp_dados_pennsylvania_df <- tidy(shp_dados_pennsylvania, region = "COUNTY_NAM") %>% 
  rename(COUNTY_NAM = id) %>% 
  left_join(shp_dados_pennsylvania@data,
            by = "COUNTY_NAM")


#Step 2: The Plot.

timestamp <- paste(format(Sys.time(), "%m_%d_%Y"),format(Sys.time(), "%H_%M_%S"))

plot_pennsylvania <- shp_dados_pennsylvania_df %>% 
  ggplot(aes(text = paste("Temp ºF: ", plot_pennsylvania$data$TEMP,
                          "<br>Local: ", plot_pennsylvania$data$COUNTY_NAM,
                          "<br>Area (Sq.Mi): ", plot_pennsylvania$data$AREA_SQ_MI)))+
  geom_polygon(aes(x = long, y = lat, group = group, fill = TEMP),
               color = "black")+
  labs(x = "Longitude",
       y = "Latitude",
       fill="Temp ºF",
       title=paste('Pennsylvania Counties',
                   paste(format(Sys.time(), "%m/%d/%Y"),format(Sys.time(), "%H:%M:%S"))),
       color = "temp") +
  scale_fill_viridis_c() +
  theme_bw()

plot_pennsylvania

#Save the images as png file
name_file <-"./Assets/png files/{timestamp}.png"
ggsave(glue(name_file),plot=plot_pennsylvania, width = 1920/72, height = 1080/72, dpi = 72)


#Save the image in html file which allows you the plotly experience
image_plotly<-ggplotly(plot_pennsylvania,tooltip = "text")
image_plotly
htmlwidgets::saveWidget(image_plotly, file = glue("{timestamp}.html"), selfcontained=TRUE) 

# Export the file as unique html file from the main folder to a specific folder
file.rename(glue("{timestamp}.html"), glue("./Assets/html files/{timestamp}.html"))
## [1] TRUE